<?php
    class Users extends ActiveRecord {
        var $change_pass = false;
        function Users()
        {
            $conf = array('table'=>DB_PREFIX.'users');
            $this->ActiveRecord($conf);
        }
        
        function validate()
        {
            $this->validates_presence_of(array('first_name','last_name','email'));            
            $this->validates_as_email('email');                        
        }
        
        function validate_on_create()
        {
            // make sure they create a password
            $this->validates_presence_of('user_password','user_login');     
            $this->validates_length_of('user_login',5);
            $this->validates_uniqueness_of('user_login');
            $this->validates_uniqueness_of('email');
            $this->validates_length_of('user_password',6);       
            $this->validates_confirmation_of('user_password');
        }
        
        function validate_on_update()        
        {
            // person is attempting to change the password
            if ( $this->change_pass && !empty($this->fields['user_password']) )
            {
                $this->validates_length_of('user_password',6);
                $this->validates_confirmation_of('user_password');
            }
            $this->validates_uniqueness_of('email');
        }
        
        function after_validation()
        {
            // hash the password
            if ( $this->change_pass && !empty($this->fields['user_password']) )
            {
                $this->saved_password = $this->get('user_password');
                $this->set('user_password', create_hash($this->fields['user_password']));
            } else {
                unset($this->fields['user_password']);
            }
        }
                
        // user set up functions
        function after_validation_on_create()
        {
            // send out email to user with the pass and stuff
            use_pixel('ActionMailer.php');
            $mail = new ActionMailer();
            $mail->AddReplyTo('noreply@'.$_SERVER['SERVER_NAME']);
            $mail->Subject = 'User Registration For: '.$_SERVER['SERVER_NAME'];
            $mail->Body = "Here are your credentials for ".
                           $_SERVER['SERVER_NAME'].
                           ".\nUsername: ".$this->get('user_login').
                           " \nPassword: ".$this->saved_password;
            $mail->AddAddress($this->get('email'), $this->get('first_name').' '.$this->get('last_name'));
            if ( !$mail->Send() )
            {
                trigger_error('Registration email could not be sent to: '.$this->get('email').' '.$mail->ErrorInfo,FATAL);
            }
        }
        
        // login functions
        function authenticate($data) 
        {
            $user_id = $this->find( array(
                                     'search'=>'first',
                                     'conditions'=> array('user_password=? and user_login=?',
                                                          array(create_hash($data['user_password']),
                                                          $data['user_login'])),
                                     'fields'=>'id'
                                         ) );            

            if( !empty($user_id['id']) ){               
                return $user_id['id'];       
            } else {
              	return false;
            }
        }
        
        function get_user_id($login)
        {
            $user_id = $this->find( array(
                                     'search'=>'first',
                                     'conditions'=> array('user_login=?',
                                                          array($login)),
                                     'fields'=>'id'
                                         ) );
            return $user_id['id'];
        }
        
        function get_user_password($login)
        {
            $user_id = $this->find( array(
                                     'search'=>'first',
                                     'conditions'=> array('user_login=?',
                                                          array($login)),
                                     'fields'=>'user_password'
                                         ) );
            return $user_id['user_password'];
        }
        
        function get_user_password_by_id($id)
        {
            $user_id = $this->find( array(
                                     'search'=>'first',
                                     'conditions'=> array('id=?',
                                                          array($id)),
                                     'fields'=>'user_password'
                                         ) );
            return $user_id['user_password'];
        }
        
        function confirm_id_and_login($id,$login)
        {
            return $this->db->GetOne('SELECT 
                                      COUNT(id) 
                                      FROM 
                                        `'.$this->table.'` 
                                      WHERE 
                                        id=? 
                                      AND 
                                        user_login=?',
                                      array( sanitize($id), sanitize($login) ) );
        } 
        
        function send_user_password($post)                                       
        {
            $user = $this->find( array('search'=>'first',
                                       'conditions'=> array('user_login=? and email=?',
                                                      array($post['user_login'],$post['email']))
                                       ) );
            if ( !empty($user) )
            {
                $new_password = substr(md5(time()),0,6);
                
                $this->load($user['id']);
                $this->set('user_password',$new_password);
                $this->set('user_password_confirm',$new_password);
                $this->change_pass = true;
                $this->save();

                use_pixel('ActionMailer.php');
                $mail = new ActionMailer();
                $mail->AddReplyTo('noreply@'.$_SERVER['SERVER_NAME']);
                $mail->Subject = 'Login retrieval: '.$_SERVER['SERVER_NAME'];
                $mail->Body = "Here are your new credentials for ".
                               $_SERVER['SERVER_NAME'].
                               ".\nUsername: ".$user['user_login'].
                               " \nPassword: ".$new_password;
                $mail->AddAddress($user['email'], $user['first_name'].' '.$user['last_name']);
                if ( !$mail->Send() )
                {                    
                    trigger_error('Retrieval email could not be sent to: '.$user['email'].' '.$mail->ErrorInfo,FATAL);
                    return false;
                }

                return true;
            }
            return false;
        }
        
        function get_users_as_list()
        {
            return $this->db->GetAssoc('SELECT id, concat(first_name," ",last_name) fullname FROM `'.$this->table.'` ORDER BY fullname');
        }
        
        function before_delete()
        {
            if ( $this->get('id') == 1 )
            {
                $this->add_error('User Delete Error','You can not delete the admin user');
                return;
            }
            
            $this->id_to_delete = $this->get('id');
        }
        
        function after_delete()
        {
            $user_id = $this->id_to_delete;
            use_model('roles','acl');
            $acl = new Acl();
            $acl->clear_user_access($user_id);
                    
            $roles = new Roles();
            $roles->clear_user_roles($user_id);
            unset($this->id_to_delete);
        }        
        
    }

?>